using System;
using System.Collections.Generic;
using System.Text;
using System.IO;

namespace SpoonCore2.OverlayNetwork.Pastry.Messages
{
	public class SearchMask
	{
		private byte _level;
		private ushort _mask;

		public SearchMask(byte level)
		{
			_level = level;
		}

		internal SearchMask(BinaryReader br)
		{
			_level = br.ReadByte();
			_mask = br.ReadUInt16();
		}

		public bool Set
		{
			get { return _mask != 0; }
		}

		public bool this[int index]
		{
			get
			{
				int mask = 1;
				mask = mask << index;
				return ((_mask & mask) > 0);
			}
			set
			{
				int mask = ((value) ? 1 : 0) << index;
				int maskR = ~(1 << index) & 0xFFFF;
				_mask = (ushort)((_mask & maskR) | mask);
			}
		}

		public byte Level
		{
			get { return _level; }
			set { _level = value; }
		}

		public byte Count
		{
			get { return 16; }
		}

		public byte[] GetBytes()
		{
			MemoryStream stream = new MemoryStream();
			BinaryWriter bw = new BinaryWriter(stream);

			bw.Write(Level);
			bw.Write(_mask);

			return stream.ToArray();
		}

		public override string ToString()
		{
			string res = "";
			for (int x = 0; x < Count; x++)
				res += this[x] ? 1 : 0;
			return res;
		}

		public void SetAll()
		{
			_mask = ushort.MaxValue;
		}

		public bool All
		{
			get { return ushort.MaxValue == _mask; }
		}

		public bool IsEmpty
		{
			get { return _mask == 0; }
		}
	}
}